# -*- coding: UTF-8 -*-
"""
@File    ：第五周-第二节-作业(线程和进程间通信).py
@Author  ：Super
@Date    ：2021/1/14
@Desc    ：线程和进程间通信
"""
from multiprocessing import Process, Lock, Queue
from threading import Thread, Lock


def process_save_file(index, lock):
    """
    多进程锁
    :param index: 进程序号
    :param lock: 锁
    :return: None
    """
    with lock:
        with open('logo.log', 'a') as f:
            f.write(str(index) + '\n')


zero = 0
lock = Lock()


def thread_save_file():
    """
    多线程锁
    :return: None
    """
    global zero
    for i in range(10 ** 5):
        with lock:
            zero += 1
            zero -= 1


def save_to_queue(index, m_queue):
    """
    通过Queue实现进程通信
    :param index:
    :param m_queue:
    :return:
    """
    m_queue.put(index)


if __name__ == '__main__':
    process_list = []
    lock = Lock()
    for i in range(10):
        p = Process(target=process_save_file, args=(i, lock))
        process_list.append(p)
        p.start()

    for p in process_list:
        p.join()
    print("完成!")

    # thread_list = []
    # for i in range(5):
    #     t = Thread(target=thread_save_file)
    #     thread_list.append(t)
    #     t.start()
    # for t in thread_list:
    #     t.join()
    # print("完成!")
    # print(zero)

    # process_list = []
    # m_queue = Queue()
    # for i in range(10):
    #     p = Process(target=save_to_queue, args=(i, m_queue))
    #     process_list.append(p)
    #     p.start()
    #
    # for p in process_list:
    #     p.join()
    #
    # while True:
    #     print(m_queue.get())
